<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80">
      <el-form-item label="请选择商铺" prop="shopIds">
        <el-select :clearable="true" v-model="queryParams.shopId" placeholder="请选择商铺">
          <el-option v-for="(shop,index) in shopListQue" :key="index" :label="shop.shopName" :value="shop.id"></el-option>
        </el-select>
      </el-form-item>
			<el-form-item label="创建时间">
				<el-date-picker
					v-model="dateRange"
					style="width: 240px"
					value-format="yyyy-MM-dd"
					type="daterange"
					range-separator="-"
					start-placeholder="开始日期"
					end-placeholder="结束日期"
				></el-date-picker>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>
		<!-- 工具栏 -->
		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button
					type="primary"
					plain
					icon="el-icon-plus"
					size="mini"
					@click="handleAdd"
					v-hasPermi="['btn.PcwlShopEnv.add']"
				>新增</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button
					type="danger"
					plain
					icon="el-icon-delete"
					size="mini"
					:disabled="multiple"
					@click="handleDelete"
					v-hasPermi="['btn.PcwlShopEnv.remove']"
				>删除</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button
					type="warning"
					plain
					icon="el-icon-download"
					size="mini"
					@click="handleExport"
					v-hasPermi="['btn.PcwlShopEnv.export']"
				>导出</el-button>
			</el-col>
			<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
		</el-row>
		<!-- 表单组件 -->
		<el-table v-loading="loading" :data="pcwlShopEnvList" @selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" align="center" />
			<el-table-column v-if="false" label="商铺环境id" align="center" prop="id" />
			<el-table-column v-if="false" label="商铺id" align="center" prop="shopId" />
			<el-table-column v-if="false" label="标签" align="center" prop="tags" />
			<el-table-column v-if="false" label="热度" align="center" prop="hot" />
			<el-table-column v-if="false" label="文件ID" align="center" prop="mediaFileId" />
      <el-table-column label="预览图" align="center" prop="picShow" width="110">
        <template slot-scope="scope">
          <el-image :src="scope.row.picShow"
                    style="width: 100px; height: 100px"
                    :preview-src-list="getImgList(scope.row.picShow)" />
        </template>
      </el-table-column>
			<el-table-column label="文件访问地址" align="center" prop="url" />
			<el-table-column label="上传人" align="center" prop="username" />
			<el-table-column label="上传时间" align="center" prop="createDate" />
			<el-table-column label="修改时间" align="center" prop="changeDate" />
			<el-table-column label="状态" align="center" prop="status" />
			<el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_is_show" :value="scope.row.status"/>
        </template>
      </el-table-column>

			<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
				<template slot-scope="scope">
					<el-button
						size="mini"
						type="text"
						icon="el-icon-edit"
						@click="handleUpdate(scope.row)"
						v-hasPermi="['btn.PcwlShopEnv.update']"
					>修改</el-button>
					<el-button
						size="mini"
						type="text"
						icon="el-icon-delete"
						@click="handleDelete(scope.row)"
						v-hasPermi="['btn.PcwlShopEnv.remove']"
					>删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<!-- 分页组件 -->
		<el-pagination :current-page="queryParams.current" :total="total" :page-size="queryParams.size" style="padding: 30px 0; text-align: center;"
			layout="total, prev, pager, next, jumper" @current-change="getList" />
		<!-- 添加或修改PcwlShopEnv对话框 -->
		<el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
			<el-form ref="form" :model="form" :rules="rules" label-width="120px" label-position="left">
        <el-form-item label="轮播图片：" prop="showPic">
          <!-- 上传图片 -->
          <el-upload class="avatar-uploader"
                     action=""
                     :show-file-list="false"
                     :http-request="uploadMainImg"
          >
            <img v-if="form.showPic" :src="form.showPic" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
				<el-form-item label="商铺环境id" prop="id">
					<el-input :disabled="true" v-model="form.id" placeholder="请输入商铺环境id" />
				</el-form-item>
        <el-form-item label="请选择商铺" prop="shopName">
          <el-select v-model="form.shopName" @change="changeSelect" placeholder="请选择商铺">
            <el-option v-for="(shop,index) in shopListQue" :key="index" :label="shop.shopName" :value="shop.id"></el-option>
          </el-select>
        </el-form-item>
				<el-form-item label="商铺id" prop="shopId">
					<el-input :disabled="true" v-model="form.shopId" placeholder="请输入商铺id" />
				</el-form-item>

				<el-form-item label="文件访问地址" prop="url">
					<el-input :disabled="true" v-model="form.url" placeholder="请输入文件访问地址" />
				</el-form-item>
				<el-form-item label="上传人" prop="username">
					<el-input :disabled="true" v-model="form.username" placeholder="请输入上传人" />
				</el-form-item>
				<el-form-item label="上传时间" prop="createDate">
					<el-input :disabled="true" v-model="form.createDate" placeholder="请输入上传时间" />
				</el-form-item>
				<el-form-item label="修改时间" prop="changeDate">
					<el-input :disabled="true" v-model="form.changeDate" placeholder="请输入修改时间" />
				</el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_is_show"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
				<el-form-item label="备注" prop="remark">
					<el-input v-model="form.remark" placeholder="请输入备注" />
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>
<!-- js脚本 -->
<script>
import { delPcwlShopEnvById, addPcwlShopEnv, updatePcwlShopEnvById, getPcwlShopEnvById,loadDataList } from "@/api/pcwl/pcwlShopEnv";
import { loadDataList as loadDataListShop } from "@/api/pcwl/pcwlShop";
import {uploadImg} from "@/api/pcwl/file";
export default {
	name: "PcwlShopEnv",
	dicts: ['sys_normal_disable','sys_is_show'],
	data() {
		return {
      shopListQue:[],
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 岗位表格数据
			pcwlShopEnvList: [],
			// 弹出层标题
			title: "",
			// 是否显示弹出层
			open: false,
			// 日期范围
			dateRange: [],
			// 查询参数
			queryParams: {
				current: 1,
				size: 10,
				id: undefined,
				shopId: undefined,
				tags: undefined,
				hot: undefined,
				mediaFileId: undefined,
				url: undefined,
				username: undefined,
				createDate: undefined,
				changeDate: undefined,
				status: undefined,
				remark: undefined,
			},
			// 表单参数
			form: {},
			// 表单校验
			rules: {
				id: [
					{ message: "商铺环境id不能为空", trigger: "blur" }
				],
				shopId: [
					{ message: "商铺id不能为空", trigger: "blur" }
				],
				tags: [
					{ message: "标签不能为空", trigger: "blur" }
				],
				hot: [
					{ message: "热度不能为空", trigger: "blur" }
				],
				mediaFileId: [
					{ message: "文件ID不能为空", trigger: "blur" }
				],
				url: [
					{ required: true,  message: "文件访问地址不能为空", trigger: "blur" }
				],
				username: [
					{ message: "上传人不能为空", trigger: "blur" }
				],
				createDate: [
					{ message: "上传时间不能为空", trigger: "blur" }
				],
				changeDate: [
					{ message: "修改时间不能为空", trigger: "blur" }
				],
				status: [
					{ message: "状态,1:正常，0:不展示不能为空", trigger: "blur" }
				],
				remark: [
					{ message: "备注不能为空", trigger: "blur" }
				],
			}
		};
	},
	created() {
    this.getShopQue();
		this.getList();
	},
	methods: {
		/** 查询商铺环境信息列表 */
		getList(currentPage=1) {
			this.loading = true;
			this.queryParams.current=currentPage;
			// loadDataList(this.queryParams).then(response => {
			loadDataList(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
				this.pcwlShopEnvList = response.data.records;
        // 使用for...of循环遍历对象数组
        for (let pcwlShopEnvtemp of this.pcwlShopEnvList) {
          pcwlShopEnvtemp.picShow=process.env.VUE_APP_MINIOURL+'/'+pcwlShopEnvtemp.url;
        }
				this.total = response.data.total;
				this.loading = false;
			});
		},
		// 取消按钮
		cancel() {
			this.open = false;
			this.reset();
		},
		// 表单重置
		reset() {
			this.form = {
				id: undefined,
				shopId: undefined,
				tags: undefined,
				hot: undefined,
				mediaFileId: undefined,
				url: undefined,
				username: undefined,
				createDate: undefined,
				changeDate: undefined,
				status: undefined,
				remark: undefined,
			};
			this.resetForm("form");
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.current = 1;
			this.getList();
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.resetForm("queryForm");
			this.handleQuery();
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map(item => item.id)
			this.single = selection.length!=1
			this.multiple = !selection.length
		},
		/** 新增按钮操作 */
		handleAdd() {
			this.reset();
			this.open = true;
			this.title = "添加商铺环境信息";
		},
		/** 修改按钮操作 */
		handleUpdate(row) {
			this.reset();
			const pcwlShopEnvId = row.id || this.ids
			getPcwlShopEnvById(pcwlShopEnvId).then(response => {
				this.form = response.data;
        this.form.showPic=process.env.VUE_APP_MINIOURL+'/'+this.form.url;
        this.getShopQueEX();
				// this.open = true;
				this.title = "修改商铺环境信息";
			});
		},
		/** 提交按钮 */
		submitForm: function() {
			this.$refs["form"].validate(valid => {
				if (valid) {
					if (this.form.id != undefined) {
						updatePcwlShopEnvById(this.form,this.form.id).then(response => {
							this.$modal.msgSuccess("修改成功");
							this.open = false;
							this.getList();
						});
					} else {
						addPcwlShopEnv(this.form).then(response => {
							this.$modal.msgSuccess("新增成功");
							this.open = false;
							this.getList();
						});
					}
				}
			});
		},
		/** 删除按钮操作 */
		handleDelete(row) {
			const pcwlShopEnvId = row.id || this.ids;
			this.$modal.confirm('是否确认删除商铺环境信息编号为"' + pcwlShopEnvId + '"的数据项？').then(function() {
				return delPcwlShopEnvById(pcwlShopEnvId);
			}).then(() => {
				this.getList();
				this.$modal.msgSuccess("删除成功");
			}).catch(() => {});
		},
		/** 导出按钮操作 */
		handleExport() {
			this.download('pcwlShopEnv/export', {
				...this.queryParams
			}, `post_${new Date().getTime()}.xlsx`)
		},
    // 获取商铺
    getShopQue(){
      let caxun={
        current:1,
        size:50
      };
      loadDataListShop(caxun).then(response => {
        this.shopListQue = response.data.records;
        // console.log('运行了？');
        // console.log(this.shopListQue);
        // console.log(this.form.shopId);
        // if (this.form.shopId!=undefined)
        // {
        //   let temp=this.shopListQue.filter(obj => obj.id === this.form.shopId);
        //   // console.log('运行了？')
        //   this.form.shopName=temp[0].shopName;
        //   this.open = true;
        // }

      });
    },
    // 获取商铺
    getShopQueEX(){
      let caxun={
        current:1,
        size:50
      };
      loadDataListShop(caxun).then(response => {
        this.shopListQue = response.data.records;
        // console.log('运行了？');
        // console.log(this.shopListQue);
        // console.log(this.form.shopId);
        if (this.form.shopId!=undefined)
        {
          let temp=this.shopListQue.filter(obj => obj.id === this.form.shopId);
          // console.log('运行了？')
          this.form.shopName=temp[0].shopName;
          this.open = true;
        }

      });
    },
    // select的Change事件
    changeSelect(val) {
      // console.log(this.shopListQue);
      // console.log(val);
      // this.form.categoryName=this.form.carouselList.categoryName;
      let tempShop = this.shopListQue.filter(obj => obj.id === val);
      console.log(tempShop);
      this.form.shopName=tempShop[0].shopName;
      this.form.shopNameEx=tempShop[0].shopName;
      console.log(this.form.shopNameEx);
      this.form.shopId=tempShop[0].id;
      console.log(this.form.shopId);
      // console.log(val);
      // 判断是否为空值，空值则为全部项
      if (!val) {
        console.log(val);
      }
      //  触发查询事件
      // this.getList();
    },
    /** 图片查看 */
    getImgList(workPhoto) {
      console.log(workPhoto);
      let arr = [];
      if (Array.isArray(workPhoto))
      {
        // if (workPhoto.length == 1) {
        //   arr.push(workPhoto[0])
        // } else if (workPhoto.length == 0)  {
        //   return arr;
        // } else {
        //   for(let i = 0;i < workPhoto.length;i++){
        //     arr.push(workPhoto[i+index])
        //     if(i+index >= workPhoto.length-1){
        //       index = 0-(i+1);
        //     }
        //   }
        // }
      }
      else
      {
        arr.push(workPhoto)
      }


      return arr;
    },
    // 上传图片, file 上传的图片对象
    uploadMainImg(file) {
      // console.log('file', file)
      const data = new FormData()
      data.append('file', file.file)
      data.append('categoryId',1)
      uploadImg(data).then(response => {
        // console.log(process.env.VUE_APP_BASE_API);
        // console.log(process.env.VUE_APP_MINIOURL);

        // 将之前的图片删除，
        this.deleteImg()
        // 回显图片
        this.form.url = response.data[0];
        this.form.showPic=process.env.VUE_APP_MINIOURL+'/'+response.data;
        // console.log(this.form.showPic);
      }).catch(error => {
        this.$message({
          type: 'error',
          message: '上传失败'
        })
      })
    },
    // 删除图片
    deleteImg() {
      // // 如果之前有图片，则删除之前的
      // if(this.form.pic && this.form.pic !== this.oldImageUrl
      // ) {
      //   // 发送请求删除
      //   commonApi.deleteImg(this.formData.imageUrl)
      // }
      console.log('删除图片', this.form.pic)
    },
	},
  // 使用 watch 监听路由变化，手动更新数据
  watch: {
    '$route': function(to, from) {
      this.getShopQue();
      this.getList();
    }
  }
};
</script>
<style scoped>
.avatar-uploader el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
//border: 2px solid black;
}
</style>

